package com.lwj.framework.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 线程池工具
 *
 * @author lwj
 *
 */
public class ThreadPoolUtil {
	private static Logger logger = LoggerFactory.getLogger(ThreadPoolUtil.class);

	/**
	 * 固定线程池默认线程数量
	 */
	public static final int DEFAULT_FIXED_SIZE_THREAD = 10;

	/**
	 * 线程池默认最大线程数量
	 */
	public static final int DEFAULT_MAX_SIZE_THREAD = 50;

	/**
	 * 线程池默认最小线程数量
	 */
	public static final int DEFAULT_MIN_SIZE_THREAD = 5;

	/**
	 * 可变线程池
	 */
	private static ExecutorService threadPool = null;

	/**
	 * 固定线程池
	 */
	private static ExecutorService fixedThreadPool = null;

	/**
	 * 单例模式获取可变线程池, 默认最少5个线程, 最多50个线程, 线程空闲一分钟销毁
	 *
	 * @return
	 */
	public static ExecutorService getThreadPool() {
		if (threadPool == null) {
			synchronized (ThreadPoolUtil.class) {
				if (threadPool == null) {
					int min = getMinSizeThread();
					int max = getMaxSizeThread();
					newThreadPool(min, max);
				}
			}
		}
		return threadPool;
	}

	/**
	 * 初始化可变线程池, 线程空闲一分钟销毁
	 *
	 * @param ninThreads 最小线程数量
	 * @param maxThreads 最大线程数量
	 */
	public static void newThreadPool(int ninThreads, int maxThreads) {
		threadPool = new ThreadPoolExecutor(ninThreads, maxThreads, 60L, TimeUnit.SECONDS,
				new LinkedBlockingQueue<Runnable>());
	}

	/**
	 * 单例模式获取固定线程池, 默认最多10个线程
	 *
	 * @return
	 */
	public static ExecutorService getFixedThreadPool() {
		if (fixedThreadPool == null) {
			synchronized (ThreadPoolUtil.class) {
				if (fixedThreadPool == null) {
					int nThreads = getFixedSizeThread();
					newFixedThreadPool(nThreads);
				}
			}
		}
		return fixedThreadPool;
	}

	/**
	 * 初始化固定线程池
	 *
	 * @param nThreads 线程池里面线程的最大数量
	 */
	public static void newFixedThreadPool(int nThreads) {
		fixedThreadPool = Executors.newFixedThreadPool(nThreads);
	}

	/**
	 * 销毁所有线程池
	 */
	public static void destroy() {
		try {
			if (threadPool != null) {
				threadPool.shutdown();
			}
		} catch (Exception e) {
			logger.error("threadPool线程池销毁异常.", e);
		}
		try {
			if (fixedThreadPool != null) {
				fixedThreadPool.shutdown();
			}
		} catch (Exception e) {
			logger.error("fixedThreadPool线程池销毁异常.", e);
		}
	}

	/**
	 * 获取固定线程池的线程数量
	 *
	 * @return
	 */
	private static int getFixedSizeThread() {
		int fixed = DEFAULT_FIXED_SIZE_THREAD;
		return fixed;
	}

	/**
	 * 获取可变线程池最小线程数量
	 *
	 * @return
	 */
	private static int getMinSizeThread() {
		int nin = DEFAULT_MIN_SIZE_THREAD;
		return nin;
	}

	/**
	 * 获取可变线程池最大线程数量
	 *
	 * @return
	 */
	private static int getMaxSizeThread() {
		int max = DEFAULT_MAX_SIZE_THREAD;
		return max;
	}

}
